package logic

import (
	"context"
	"fmt"
	"vipshop/models/cache"
	"vipshop/models/mysql"
	"vipshop/pkg"

	"vipshop/vipshoprpc/internal/svc"
	"vipshop/vipshoprpc/vipshoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *vipshoprpc.RegisterRequest) (*vipshoprpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var vip mysql.User
	mysql.DB.Debug().Where("id = ?", vip.ID).Find(&vip)
	if vip.ID != 0 {
		return nil, fmt.Errorf("账号已存在")
	}
	res, _ := cache.Rdb.Get(cache.Ctx, "captcha"+in.Username).Result()
	if res != in.CaptchaCode {
		return nil, fmt.Errorf("图形验证码错误")
	}
	cmd, _ := cache.Rdb.Get(cache.Ctx, "sendSms"+in.Mobile).Result()
	if cmd != in.SendSmsCode {
		return nil, fmt.Errorf("短信验证码错误")
	}
	var vips = mysql.User{
		Username: in.Username,
		Mobile:   in.Mobile,
		Password: pkg.Md5(in.Password),
	}
	mysql.DB.Debug().Create(&vips)
	return &vipshoprpc.RegisterResponse{
		Id: int64(vip.ID),
	}, nil
}
